package exercise;

import java.util.*;

public class LCode1657 {
    // 返回 true 的条件:
    // 1. 长度相等
    // 2. 出现频率相同
    // 3. 字符串 1 中不能出现字符串 2 中没有的字母, 反之亦然
    public boolean closeStrings1(String word1, String word2) {
        if (word1.length() != word2.length()) {
            return false;
        }

        Map<Character, Integer> map1 = new HashMap<>();
        Map<Character, Integer> map2 = new HashMap<>();

        for (int i = 0; i < word1.length(); i++) {
            char ch1 = word1.charAt(i);
            char ch2 = word2.charAt(i);

            if (!word1.contains(String.valueOf(ch2)) || !word2.contains(String.valueOf(ch1))) {
                return false;
            }

            if (!map1.containsKey(ch1)) {
                map1.put(ch1, 1);
            } else {
                map1.put(ch1, map1.get(ch1) + 1);
            }

            if (!map2.containsKey(ch2)) {
                map2.put(ch2, 1);
            } else {
                map2.put(ch2, map2.get(ch2) + 1);
            }
        }

        PriorityQueue<Integer> l1 = new PriorityQueue<>();
        PriorityQueue<Integer> l2 = new PriorityQueue<>();


        for (int i = 0; i < word1.length(); i++) {
            int x = map1.getOrDefault(word1.charAt(i), -1);
            if (x != -1) {
                l1.add(x);
                map1.remove(word1.charAt(i));
            }

            int y = map2.getOrDefault(word2.charAt(i), -1);
            if (y != -1) {
                l2.add(y);
                map2.remove(word2.charAt(i));
            }
        }

        if (l1.size() != l2.size()) {
            return false;
        }

        while (!l1.isEmpty()) {
            if (!l1.poll().equals(l2.poll())) {
                return false;
            }
        }
        return true;
    }

    public boolean closeStrings(String word1, String word2) {
        if (word1.length() != word2.length()) {
            return false;
        }
        // 计数数组
        int[] arr1 = new int[26];
        int[] arr2 = new int[26];

        for (char ch : word1.toCharArray()) {
            arr1[ch - 'a']++;
        }

        for (char ch : word2.toCharArray()) {
            arr2[ch - 'a'] ++;
        }

        for (int i = 0; i < 26; i++) {
            if (arr1[i] > 0 && arr2[i] == 0 || arr2[i] > 0 && arr1[i] == 0) {
                return false;
            }
        }

        Arrays.sort(arr1);
        Arrays.sort(arr2);

        return Arrays.equals(arr1, arr2);
    }


    public static void main(String[] args) {
        LCode1657 lCode1657 = new LCode1657();

        String s1 = "cabbba";
        String s2 = "aabbss";

        System.out.println(lCode1657.closeStrings(s1, s2));
    }
}
